package org.huangrui.controller;

import com.alibaba.cloud.ai.dashscope.api.DashScopeImageApi;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageModel;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageOptions;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.net.URI;
import java.net.URL;

/**
 * @Author hr
 * @Create 2025-11-11 14:55
 **/
@Slf4j
@RestController
public class ImageModelController {
    @Autowired
    private DashScopeImageModel dashScopeImageModel;
    // http://localhost:8001/image?prompt=一个中国小城
    @GetMapping("/image")
    public void image(@RequestParam(value = "prompt", defaultValue = "一个中国小城") String prompt,
                        HttpServletResponse  response) {
        ImageResponse imageResponse = dashScopeImageModel.call(new ImagePrompt(prompt,
                DashScopeImageOptions.builder()
                        .withModel(DashScopeImageApi.DEFAULT_IMAGE_MODEL)
                        .withN(1)
                        .withHeight(1024)
                        .withWidth(1024)
                        .build()));
        //获取生成图像的地址
        String imageUrl = imageResponse.getResult().getOutput().getUrl();
        //在浏览器输出
        try {
            URL url = URI.create(imageUrl).toURL();
            InputStream ins = url.openStream();
            response.setHeader("Content-Type", MediaType.IMAGE_JPEG_VALUE);
            response.getOutputStream().write(ins.readAllBytes());
            response.getOutputStream().flush();
        }  catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
